package com.zhoulu.service.book;

import com.zhoulu.domain.book.BookBean;
import com.zhoulu.domain.user.UserBean;
import com.zhoulu.domain.util.LayuiResult;
import com.zhoulu.mapper.book.BookMapper;
import com.zhoulu.util.PageRequest;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;


@Service
public class BookService {

    private static final String bookImagePath = "bookImages/";

    @Autowired
    private BookMapper bookMapper;

    /**
     * 查询图书信息集合分页
     * @param bookBean
     * @return
     */
    public PageInfo<BookBean> findBookListPage(BookBean bookBean, PageRequest pageRequest){
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());
        PageInfo<BookBean> pageInfo = new PageInfo<BookBean>(bookMapper.findBookList(bookBean));
        return pageInfo;
    }

    /**
     * 查询图书信息集合
     * @param bookBean
     * @return
     */
    public List<BookBean> findBookList(BookBean bookBean){
        return bookMapper.findBookList(bookBean);
    }

    /**
     * 新增图书
     * @param bookBean
     */
    @Transactional(rollbackFor = Exception.class)
    public LayuiResult insertBook(BookBean bookBean){
        try {
            bookBean.setCreator(((UserBean) SecurityUtils.getSubject().getPrincipal()).getUsername());
            String destPath = ResourceUtils.getURL("classpath:").getPath() + "static/" + bookImagePath + bookBean.getFile().getOriginalFilename();
            bookBean.setImagePath(bookImagePath + bookBean.getFile().getOriginalFilename());
            bookMapper.insertBook(bookBean);
            File destFile = new File(destPath);
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            bookBean.getFile().transferTo(destFile);
            return LayuiResult.success("新增图书成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return LayuiResult.error("新增图书失败" + e.getMessage());
        } catch (java.io.IOException io){
            io.printStackTrace();
            return LayuiResult.error("新增图书失败" + io.getMessage());
        }
    }

    /**
     * 修改图书信息
     * @param bookBean
     */
    public void updateBook(BookBean bookBean){
        bookMapper.updateBook(bookBean);
    }

    /**
     * 删除图书
     * @param bookNo 图书编号
     */
    public void deleteBookByNo(String bookNo){
        bookMapper.deleteBookByNo(bookNo);
    }
}
